<?php
class GuestModel extends MY_Model {
	
	function GuestModel() {
		parent::MY_Model ('guest');
	}
	
	function get_guests_by_userid($userid, $offset) {
		$sql = "SELECT * FROM guest WHERE user_id = ? ORDER BY create_time DESC LIMIT ? , 10";
		$query = $this->db->query($sql, array($userid, (int)$offset));
		$data = $query->result();
		if (count($data) == 0) {
			return false;
		} else {
			return $data;
		}
	}
	
	function get_count_guests_by_userid($userid) {
		$sql = "SELECT count(*) as num FROM guest WHERE user_id = ?";
		$query = $this->db->query($sql, array($userid));
		$data = $query->row_array();
		return $data['num'];
	}
	
	function get_guests_by_condition($data) {
		$this->db->where ("user_id", $data['user_id']);
		if ($data['i_name'] != "") {
			$this->db->like('i_name', $data['i_name']); 
		}
		
		if ($data['i_category'] != "") {
			$this->db->where('i_category', $data['i_category']);
		}
		
		if ($data['b_i_category'] != "") {
			$this->db->where('b_i_category', $data['b_i_category']);
		}

		if ($data['i_flag'] != "") {
			$this->db->where('i_flag', $data['i_flag']);
		}
		
		$this->db->order_by("create_time", "DESC");
		 
		$this->db->limit(10, $data['offset']);

		$query = $this->db->get('guest');
		
		return $query->result();
	}
	
	function get_count_by_condtion($data) {
		$this->db->where ("user_id", $data['user_id']);
		if ($data['i_name'] != "") {
			$this->db->like('i_name', $data['i_name']); 
		}
		
		if ($data['i_category'] != "") {
			$this->db->where('i_category', $data['i_category']);
		}
		
		if ($data['b_i_category'] != "") {
			$this->db->where('b_i_category', $data['b_i_category']);
		}

		if ($data['i_flag'] != "") {
			$this->db->where('i_flag', $data['i_flag']);
		}
		
 		return $this->db->count_all_results('guest');
	}
	
	function save_guest($data) {
		$data ['b_i_category'] = $this->get_b_category($data['i_category']);
		$data ['create_time'] = time ();
		$this->db->insert ( 'guest', $data );
	}
	
	function get_b_category($i_category) {
		if ( in_array($i_category,array("1", "2", "3"))) {
			return "1";
		}
		
		if ( in_array($i_category,array("4", "5", "6"))) {
			return "2";
		}
		
		if ( in_array($i_category,array("7", "8", "9"))) {
			return "3";
		}
		
		if ( in_array($i_category,array("10", "11", "12"))) {
			return "4";
		}
		
	}
	
	function update_guest($data) {
		$data ['create_time'] = time ();
		$data ['b_i_category'] = $this->get_b_category($data['i_category']);
		$this->db->where ( 'id', $data ['id'] );
		$this->db->update ( 'guest', $data );
	}
	
	
}